package com.xhsj.user.hr.process.tbLearningGarden.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.lowagie.text.DocumentException;
import com.xhsj.user.hr.base.BaseParam;
import com.xhsj.user.hr.base.BaseService;
import com.xhsj.user.config.UploadPathConfig;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.dto.tbLearningGarden.*;
import com.xhsj.user.hr.process.hrBecomeRegular.service.TbHrApprovalBecomeRegularApplyService;
import com.xhsj.user.hr.process.hrTransferJob.query.CompletedTransferJobApplyQuery;
import com.xhsj.user.hr.process.hrTransferJob.query.MyTransferJobApplyListQuery;
import com.xhsj.user.hr.process.hrTransferJob.query.RunTransferJobApplyListQuery;
import com.xhsj.user.hr.process.processDefinition.query.ProcessNodeQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentApply;
import com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentApplyFile;
import com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentViewDept;
import com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentViewPerson;
import com.xhsj.user.hr.process.tbLearningGarden.mapper.TbLearningGardenContentApplyFileMapper;
import com.xhsj.user.hr.process.tbLearningGarden.mapper.TbLearningGardenContentApplyMapper;
import com.xhsj.user.hr.process.tbLearningGarden.mapper.TbLearningGardenContentViewDeptMapper;
import com.xhsj.user.hr.process.tbLearningGarden.mapper.TbLearningGardenContentViewPersonMapper;
import com.xhsj.user.hr.process.tbLearningGarden.query.*;
import com.xhsj.user.hr.process.tbLearningGarden.query.FindUnReadListQuery;
import com.xhsj.user.hr.process.tbLearningGarden.query.GetLearningGardenContentApplyDetailQuery;
import com.xhsj.user.hr.process.tbLearningGarden.query.MyLearningGardenContentApplyListQuery;
import com.xhsj.user.hr.process.tbLearningGarden.query.RunLearningGardenContentApplyListQuery;
import com.xhsj.user.hr.process.tbLearningGarden.vo.FindUnReadListVo;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 学习园地-内容 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Nov 20, 2020 10:59:29 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbLearningGardenContent")
public class TbLearningGardenContentApplyService extends BaseService<TbLearningGardenContentApplyMapper, TbLearningGardenContentApply> {
    @Autowired
    private TbLearningGardenContentApplyMapper dao;

    @Autowired
    private TbLearningGardenContentApplyFileService tbLearningGardenContentApplyFileService;

    // 流程-任务审核表 服务实现类
    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    @Autowired
    private TbHrApprovalBecomeRegularApplyService tbHrApprovalBecomeRegularApplyService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    // 角色信息表 Mapper 接口
    @Autowired
    private TbGlobalRoleMapper tbGlobalRoleMapper;

    @Autowired
    private UploadPathConfig uploadPath;

    @Autowired
    private TbLearningGardenContentViewPersonService tbLearningGardenContentViewPersonService;

    @Autowired
    private TbLearningGardenContentViewDeptService tbLearningGardenContentViewDeptService;


    /**
     * 保存
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    @Override
    //@CacheEvict(cacheNames="TbLearningGardenContent", allEntries=true)
    public boolean save(TbLearningGardenContentApply entity) {
        return super.save(entity);
    }

    /**
     * 通过id获取数据
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbLearningGardenContentApply getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * 通过id删除数据
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    @Override
    //@CacheEvict(cacheNames="TbLearningGardenContent", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 批量删除数据
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

    /**
     * 分页查询数据
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbLearningGardenContentApply> selectPage(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        TbLearningGardenContentApply entity = JSON.parseObject(JSON.toJSONString(data), TbLearningGardenContentApply.class);
        Page<TbLearningGardenContentApply> page = new Page(currentPage, pageSize);
        QueryWrapper<TbLearningGardenContentApply> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    /**
     * 查询所有数据
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    @Override
    //@Cacheable(value = "TbLearningGardenContent",sync = true)
    public List<TbLearningGardenContentApply> selectAll() {
        return super.selectAll();
    }

    /**
     * 学习园地-内容 保存/修改/发布
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    public ApprovalQuery savePush(TbLearningGardenContentDto data) throws Exception {

        if (StringUtils.isNotBlank(data.getApply().getId())) { // 删除查阅部门和查阅人员数据
            tbLearningGardenContentViewPersonService.delByDataId(data.getApply().getId());
            tbLearningGardenContentViewDeptService.delByDataId(data.getApply().getId());
        }

        // 保存/修改/发布
        TbLearningGardenContentApply apply = data.getApply();
        if (!super.save(data.getApply())) {
            throw new Exception("学习园地-内容保存/修改/发布异常");
        }

        List<Long> departmentIds = apply.getDepartmentIds();
        // 保存查阅部门
        if (departmentIds != null) {
            List<TbLearningGardenContentViewDept> depts = Lists.newArrayList();
            for (Long departmentId : departmentIds) {
                TbLearningGardenContentViewDept viewDept = new TbLearningGardenContentViewDept();
                viewDept.setDataId(apply.getId());
                viewDept.setDeptId(departmentId);
                viewDept.setCreateBy(UserUtils.getLoginAppUser().getUserId());
                viewDept.setUpdateBy(UserUtils.getLoginAppUser().getUserId());
                viewDept.setCreateDate(new Date());
                viewDept.setUpdateDate(new Date());
                depts.add(viewDept);
            }
            tbLearningGardenContentViewDeptService.saveBatch(depts);
        }

        List<Long[]> userIds = apply.getUserIds();
        // 保存查阅人员
        if (userIds != null) {
            List<TbLearningGardenContentViewPerson> persons = Lists.newArrayList();
            for (Long[] userId : userIds) {
                TbLearningGardenContentViewPerson viewPerson = new TbLearningGardenContentViewPerson();
                viewPerson.setDataId(apply.getId());
                viewPerson.setDeptId(userId[0]);
                viewPerson.setUserId(userId[1]);
                viewPerson.setCreateBy(UserUtils.getLoginAppUser().getUserId());
                viewPerson.setUpdateBy(UserUtils.getLoginAppUser().getUserId());
                viewPerson.setCreateDate(new Date());
                viewPerson.setUpdateDate(new Date());
                persons.add(viewPerson);
            }

            tbLearningGardenContentViewPersonService.saveBatch(persons);
        }


        ApprovalQuery approvalQuery = new ApprovalQuery();
        ProcessNodeQuery processNodeQuery = new ProcessNodeQuery();
        // 流程审批
        if (apply.getSubmitStatus() == 1) {
            HandleAuditDto handleAuditDto = new HandleAuditDto();
            handleAuditDto.setDataId(apply.getId());
            handleAuditDto.setProposerId(apply.getCreateBy());
            handleAuditDto.setCreateBy(apply.getCreateBy());
            handleAuditDto.setApplyType(12);
            // 发布人是总经理直接完结
            List<Long> roleIdsByUserId = tbGlobalUserMapper.getRoleIdsByUserId(apply.getPublisherId());
            if (roleIdsByUserId.contains(new Long(3))) {
                // 执行流程
                processNodeQuery = tbGlobalApprovalTaskService.startHandleAuditLearningGardenNoLeader(handleAuditDto, Long.valueOf(apply.getPublishingDepartmentId() + ""));
            } else {
                // 上级领导
                Long leaderId = tbGlobalUserMapper.getLeaderId(apply.getPublisherId());
                handleAuditDto.setUserId(Arrays.asList(String.valueOf(leaderId).split(",")));
                // 执行流程
                processNodeQuery = tbGlobalApprovalTaskService.startHandleAuditLearningGarden(handleAuditDto, Long.valueOf(apply.getPublishingDepartmentId() + ""));
            }
            // 修改学习园地内容申请表节点名称和节点id
            approvalQuery = this.updateTbLearningGardenContentApply(handleAuditDto, processNodeQuery, apply.getShortMessage(),apply.getPublisherName());
        }
        // 保存相关文件
        this.saveFile(apply.getWatermark(), processNodeQuery.getNodeName(), data.getApply().getId(), data.getApplyFileList());
        return approvalQuery;
    }

    // 保存相关文件
    public void saveFile(Integer watermark, String nodeName, Long dataId, List<TbLearningGardenContentApplyFile> applyFileList) throws Exception {
        // 删除申请对应的文件
        tbLearningGardenContentApplyFileService.deleteFile(dataId);
        // 保存相关文件
        for (TbLearningGardenContentApplyFile file : applyFileList) {
            // 添加水印
            if (watermark == 0 && "完结".equals(nodeName)) {
                file = this.addWatermark(file);
            }
            file.setId(null);
            file.setLearningGardenId(dataId);
            if (!tbLearningGardenContentApplyFileService.save(file)) {
                throw new Exception("学习园地-内容保存相关文件异常");
            }
        }
    }

    // 添加水印
    public TbLearningGardenContentApplyFile addWatermark(TbLearningGardenContentApplyFile file) throws IOException, DocumentException {
        String path = "erp-user";
        String date = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String upload = uploadPath.getTemp() + path + "/" + date;

        String fileUrl = file.getFileUrl();

        String inputPath = uploadPath.getPath() + "/" + fileUrl.substring(fileUrl.lastIndexOf("download/") + 9);

        int fixPosition = file.getFileName().lastIndexOf(".");
        String newFileName = IdGen.uuid() + "." + file.getFileName().substring(fixPosition + 1);
        WaterPrintUtils.setWatermark(upload + "/" + newFileName,
                inputPath,
                "芯海内部文件   请勿外传");
        file.setFileName(newFileName);
        file.setFileUrl("/file/download" + uploadPath.getDirectory() + path + "/" + date + "/" + newFileName);
        file.setDelUrl("/file/download" + uploadPath.getDirectory() + path + "/" + date + "/" + newFileName);
        return file;
    }

    // 修改学习园地内容申请表节点名称和节点id
    public ApprovalQuery updateTbLearningGardenContentApply(HandleAuditDto data, ProcessNodeQuery processNodeQuery, Integer shortMessage,String fullName) throws Exception {
        //修改产品申请表节点名称和节点id
        TbLearningGardenContentApply tbHrApprovalEntryApply = new TbLearningGardenContentApply();
        tbHrApprovalEntryApply.setId(data.getDataId());
        tbHrApprovalEntryApply.setNodeName(processNodeQuery.getNodeName());
        tbHrApprovalEntryApply.setNodeId(processNodeQuery.getNodeId());
        tbHrApprovalEntryApply.setBusinessId(data.getBusinessId());
        tbHrApprovalEntryApply.setDelFlag(processNodeQuery.getDelFlag());
        if (!this.save(tbHrApprovalEntryApply)) {
            throw new Exception("修改学习园地内容申请表节点名称信息异常");
        }
        if(shortMessage != null)
        if ("完结".equals(processNodeQuery.getNodeName()) && shortMessage == 0) {
            List<Long> onTheJobEmployeesUserId = tbGlobalUserMapper.getOnTheJobEmployeesUserId();
            processNodeQuery.setUserId(onTheJobEmployeesUserId);
            return tbHrApprovalBecomeRegularApplyService.setApprovalQuery(data.getDataId(), 12, MessageConstant.MSG_11, processNodeQuery,fullName);
        }
        // 消息参数
        return tbHrApprovalBecomeRegularApplyService.setApprovalQuery(data.getDataId(), 12, MessageConstant.MSG_11, processNodeQuery,fullName);
    }


    /**
     * 学习园地-内容 删除
     *
     * @author liuqinghua
     * @date Nov 20, 2020 10:59:29 AM
     */
    public void deletePush(Integer id) {
        // 删除
        dao.deletePush(id);
    }

    /**
     * 我的学习园地内容申请列表
     *
     * @author liuqinghua
     * @date Nov 23, 2020 10:59:29 AM
     */
    public IPage<MyLearningGardenContentApplyListQuery> myLearningGardenContentApplyList(MyLearningGardenContentApplyListDto data) {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        Page<MyLearningGardenContentApplyListQuery> page = new Page<>(data.getPage(), data.getSize());
        return dao.myLearningGardenContentApplyList(page, userId, data);
    }

    /**
     * 待审核学习园地内容申请列表
     *
     * @author liuqinghua
     * @date Nov 23, 2020 10:07:11 AM
     */
    public IPage<RunLearningGardenContentApplyListQuery> runLearningGardenContentApplyList(RunLearningGardenContentApplyListDto data) {
        Page<RunLearningGardenContentApplyListQuery> page = new Page<>(data.getPage(), data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        // 获取用户角色id
        List<Long> roleList = tbGlobalRoleMapper.getRoleListByUserId(userId);
        return dao.runLearningGardenContentApplyList(page, userId, roleList, data);
    }

    /**
     * @Description:待审核学习园地内容详情
     * @Param:dataId
     * @Author: liuqinghua
     * @Date: 2020/11/23
     */
    public GetLearningGardenContentApplyDetailQuery getLearningGardenContentApplyDetail(Long dataId) {
        GetLearningGardenContentApplyDetailQuery learningGardenContentApplyDetail = dao.getLearningGardenContentApplyDetail(dataId);

        List<Long> deptIds = tbLearningGardenContentViewDeptService.getDeptIdByDataId(dataId);

        List<String> deptAndUserIds = tbLearningGardenContentViewPersonService.getUserIdsByDataId(dataId);
        List<Long[]> objects = Lists.newArrayList();
        for (String deptAndUserId : deptAndUserIds) {
            String[] split = deptAndUserId.split(",");
            Long[] longs = new Long[2];
            longs[0] = Long.valueOf(split[0]);
            longs[1] = Long.valueOf(split[1]);
            objects.add(longs);
        }

        learningGardenContentApplyDetail.setUserIds(objects);
        learningGardenContentApplyDetail.setDepartmentIds(deptIds);

        return dao.getLearningGardenContentApplyDetail(dataId);
    }

    /**
     * 学习园地-内容审核
     *
     * @author liuqinghua
     * @date Nov 23, 2020 10:59:29 AM
     */
    public ApprovalQuery approvalLearningGardenContentApply(ApprovalLearningGardenContentApplyDto data) throws Exception {
        // 执行流程
        HandleAuditDto handleAuditDto = StringUtils.toJavaBean(data, HandleAuditDto.class);
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(handleAuditDto);

        TbLearningGardenContentApply byId = this.getById(data.getDataId());
        // 修改学习园地内容申请表节点名称和节点id
        ApprovalQuery approvalQuery = this.updateTbLearningGardenContentApply(handleAuditDto, processNodeVo, data.getShortMessage(),byId==null?"":byId.getPublisherName());

        // 水印设置
        if (data.getWatermark() == 0 && "完结".equals(processNodeVo.getNodeName())) {
            // 获取申请相关的文件
            QueryWrapper<TbLearningGardenContentApplyFile> queryWrapper = new QueryWrapper();
            queryWrapper.eq("learning_garden_id", handleAuditDto.getDataId());
            List<TbLearningGardenContentApplyFile> list = tbLearningGardenContentApplyFileService.list(queryWrapper);
            this.saveFile(data.getWatermark(), processNodeVo.getNodeName(), data.getDataId(), list);
        }

        return approvalQuery;
    }


    /**
     * 查询未阅读信息列表
     *
     * @author 苏小林
     * @date 2020/11/23 14:44
     * @param: baseParam
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentApply>
     */
    public IPage<FindUnReadListVo> findUnReadListByUserId(FindUnReadListQuery data) {
        LocalDate now = LocalDate.now();
        Long userId = UserUtils.getLoginAppUser().getUserId();

        Integer type = data.getType();
        if (type == 0) { // 0 未读数据 1 全部数据
            Page<TbLearningGardenContentApply> page = new Page<>(data.getPage(), data.getSize());


            IPage<FindUnReadListVo> iPage = dao.findUnReadListByUserId(page, now, userId);
            if (iPage.getRecords().size() == 0) { // 没有未读的就显示已读的
                iPage = dao.findByImportantFlag(page, now, userId);
            }

            return iPage;
        } else {
            Page<TbLearningGardenContentApply> page = new Page<>(data.getPage(), data.getSize());
            return dao.findAllReadListByUserId(page, now, userId);
        }

    }

    /**
     * @Description: 已审核的学习园地内容申请列表
     * @Author: liuqinghua
     * @Date: 2020/11/24
     */
    public IPage<CompletedLearningGardenContentApplyQuery> completedLearningGardenContentApplyList(RunLearningGardenContentApplyListDto data) {
        Page<CompletedLearningGardenContentApplyQuery> page = new Page<>(data.getPage(), data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        return dao.completedLearningGardenContentApplyList(page, userId, data);
    }

    /**
     * @Description: 学习园地-内容重新提交
     * @Author: liuqinghua
     * @Date: 2020/11/25
     */
    public ApprovalQuery returnPush(ReturnPushDto data) throws Exception {

        // 删除数据
        HandleAuditDto auditDto = data.getHandleAuditDto();
        Long processTaskId = auditDto.getProcessTaskId();

        tbGlobalApprovalTaskService.delById(processTaskId);
        tbGlobalApprovalTaskService.delHisTask(auditDto.getBusinessId(),auditDto.getDataId());

        TbLearningGardenContentDto target = new TbLearningGardenContentDto();
        BeanUtils.copyProperties(data,target);
        ApprovalQuery approvalQuery = this.savePush(target);

        return approvalQuery;
    }
}
